//
//  Utility.m
//  CloudTravel
//
//  Created by hetao on 10-12-5.
//  Copyright 2010 oulin. All rights reserved.
//

#import "Utility.h"

#import <arpa/inet.h>
#define picMidWidth 200
#define picSmallWidth 100
@interface Utility (){
    UITextField *accountField,*passField;
    NSString *phoneNum;
    UIAlertView *alertview;
}
@property (nonatomic,strong) NSURL *phoneNumberURL;
@property (nonatomic,copy) void (^finished)(NSString *account,NSString *pass);
@end

@implementation Utility

static Utility *_utilityinstance=nil;
static dispatch_once_t utility;

+(id)Share
{
    dispatch_once(&utility, ^ {
        _utilityinstance = [[Utility alloc] init];
    });
	return _utilityinstance;
}

#pragma mark - remove webview background
+ (void)removeWebViewBlackColor:(UIWebView *)webview{
    webview.backgroundColor=[UIColor clearColor];
    for (UIView *aView in [webview subviews])
    {
        if ([aView isKindOfClass:[UIScrollView class]])
        {
            [(UIScrollView *)aView setShowsVerticalScrollIndicator:NO]; //右侧的滚动条 （水平的类似）
            
            for (UIView *shadowView in aView.subviews)
            {
                
                if ([shadowView isKindOfClass:[UIImageView class]])
                {
                    shadowView.hidden = YES;  //上下滚动出边界时的黑色的图片 也就是拖拽后的上下阴影
                }
            }
        } 
    }
}

#pragma mark -
#pragma mark makeCall
- (NSString*) cleanPhoneNumber:(NSString*)phoneNumber
{
    return [[[[phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""]
									stringByReplacingOccurrencesOfString:@"-" withString:@""]
										stringByReplacingOccurrencesOfString:@"(" withString:@""] 
											stringByReplacingOccurrencesOfString:@")" withString:@""];
    
    //return number1;    
}
- (void) makeCall:(NSString *)phoneNumber
{
	if (!phoneNumber||[phoneNumber isEqualToString:@""]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:Lang( @"error",@"错误")
														message:Lang( @"Error Number",@"号码有误")
													   delegate:self
											  cancelButtonTitle:Lang(@"确定",@"OK")
											  otherButtonTitles:nil];
		[alert show];
		//[alert release];
		
		return;
	}
    NSString* numberAfterClear = [self cleanPhoneNumber:phoneNumber];
    
    self.phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
													message:phoneNumber
												   delegate:self
										  cancelButtonTitle:Lang(@"取消", @"cancel")
										  otherButtonTitles:Lang(@"拨打", @"Call"),nil];
	[alert show];
	//[alert release];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertview.title.length>0) {
        UINavigationController *nav = (UINavigationController*) [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        if(![nav.visibleViewController isKindOfClass:NSClassFromString(@"ScanViewController")]){
            if([nav.visibleViewController isKindOfClass:NSClassFromString(@"ViewController")]){
//                [nav.visibleViewController performSelector:@selector(scanButtonClicked:) withObject:nil];
            }
        }
    }else{
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:self.phoneNumberURL];
        }
    }
}

#pragma mark -
#pragma mark validateEmail
+ (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}
#pragma mark validateTel
+ (BOOL) validateTel: (NSString *) candidate {
    NSString *telRegex = @"^1[34578]\\d{9}$";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
	
    return [telTest evaluateWithObject:candidate];
//    if (candidate.length>=5) {
//        NSString *str = [NSString stringWithFormat:@"%.0f",candidate.doubleValue];
//        return [str isEqualToString:candidate];
//    }else{
//        return NO;
//    }
}
+ (BOOL)validateMac:(NSString*) candidate {
    if (!candidate.length) {
        return NO;
    }
    NSString *macRegex = @"^([0-9a-fA-F]{2})(([/\\s:][0-9a-fA-F]{2}){5})$";
    NSPredicate *macTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", macRegex];
    return [macTest evaluateWithObject:candidate];
}
+ (BOOL)validateUUID:(NSString*) candidate {
    if (!candidate.length) {
        return NO;
    }
    NSString *uuidRegex = @"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
    NSPredicate *uuidTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", uuidRegex];
    return [uuidTest evaluateWithObject:candidate];
}
#pragma ImagePeSize
-(CGFloat)percentage:(NSString*)per width:(NSInteger)width
{
    if (per) { 
        NSArray *stringArray = [per componentsSeparatedByString:@"*"];
        
        if ([stringArray count]==2) {
            CGFloat w=[[stringArray objectAtIndex:0] floatValue];
            CGFloat h=[[stringArray objectAtIndex:1] floatValue];
            if (w>=width) {
                return h*width/w;
            }else{
                return  h;
            }
        }
    }
    return width;
}

//判断ios版本AVAILABLE
- (BOOL)isAvailableIOS:(CGFloat)availableVersion
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=availableVersion) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark TimeTravel
+(NSString *)convertDateToLocalTime: (NSString *)toDate {
    if (!toDate.length) {
        return @"";
    }
    CGFloat time = [toDate floatValue]/1000;
    NSDate *forDate = [NSDate dateWithTimeIntervalSince1970:time];
    NSTimeZone *nowTimeZone = [NSTimeZone localTimeZone];
    NSInteger timeOffset = [nowTimeZone secondsFromGMTForDate:forDate];
    NSDate *newDate = [forDate dateByAddingTimeInterval:timeOffset];
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [dateFormatter stringFromDate:newDate];
    
}

+ (NSString *)timeInBeijing {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    formatter.locale = locale;
    return [formatter stringFromDate:[NSDate date]];
}

- (NSString*)timeToNow:(NSString*)theDate
{
    if (!theDate) {
        return nil;
    }
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[dateFormatter dateFromString:theDate];
    if (!d) {
        return theDate;
    }
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=(now-late)>0 ? (now-late) : 0;
    
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@ 分前", timeString];
        
    }else if (cha/3600>1 && cha/3600<24) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@ 小时前", timeString];
    }
    else
    {
       /* if (needYear) {
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        }
        else
        {
            [dateFormatter setDateFormat:@"MM-dd"];
        }
        timeString=[dateFormatter stringFromDate:d];*/
        timeString = [NSString stringWithFormat:@"%.0f 天前",cha/3600/24];
    }
    
    return timeString;
}
+ (void)alertError:(NSString*)content
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showErrorWithStatus:content];
    });
}
+ (void)alertSuccess:(NSString*)content
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showSuccessWithStatus:content];
    });
}
- (void)alert:(NSString*)content
{
    [self alert:content delegate:nil];
}
- (void)alertContentCancel:(NSString*)content delegate:(id)delegate
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (alertview) {
            alertview.delegate = nil;
            [alertview dismissWithClickedButtonIndex:-1 animated:NO];
        }
        alertview =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"友情提示",nil) message:content delegate:delegate cancelButtonTitle:Lang(@"Cancel",@"取消") otherButtonTitles:NSLocalizedString(@"好的",nil), nil] ;[alertview show];
    });
}
- (void)alert:(NSString*)content delegate:(id)delegate
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (alertview) {
            alertview.delegate = nil;
            [alertview dismissWithClickedButtonIndex:-1 animated:NO];
        }
        alertview =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"友情提示",nil) message:content delegate:delegate cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"好的",nil), nil] ;[alertview show];
    });
}

- (void)alert:(NSString*)content delegate:(id)delegate buttons:(NSArray*)buttons
{
    [self alert:content delegate:delegate buttons:buttons tag:0];
}

- (void)alert:(NSString*)content delegate:(id)delegate buttons:(NSArray*)buttons tag:(NSInteger)tag
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (alertview) {
            alertview.delegate = nil;//防止意外触发回调
            [alertview dismissWithClickedButtonIndex:-1 animated:NO];
        }
        alertview =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"友情提示",nil) message:content delegate:delegate cancelButtonTitle:nil otherButtonTitles: nil];
        if(tag)alertview.tag = tag;
        for (NSString *title in buttons) {
            [alertview addButtonWithTitle:title];
        }
        [alertview show];
    });
}
/**
 *	保存obj的array到本地，如果已经存在会替换本地。
 *
 *	@param	obj	待保存的obj
 *	@param	key	保存的key
 */
+ (void)saveToArrayDefaults:(id)obj forKey:(NSString*)key
{
    if(key&&obj)[self saveToArrayDefaults:obj replace:obj forKey:key];
}
+ (void)saveToArrayDefaults:(id)obj replace:(id)oldobj forKey:(NSString*)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults valueForKey:key];
    
    NSMutableArray *marray = [NSMutableArray array];
    if (!oldobj) {
        oldobj = obj;
    }
    if (array) {
        [marray addObjectsFromArray:array];
        if ([marray containsObject:oldobj]) {
            [marray replaceObjectAtIndex:[marray indexOfObject:oldobj] withObject:obj];
        }else{
            [marray addObject:obj];
        }
    }else{
      [marray addObject:obj];  
    }
    [defaults setValue:marray forKey:key];
    [defaults synchronize];
}

+ (BOOL)removeForArrayObj:(id)obj forKey:(NSString*)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults valueForKey:key];
    
    NSMutableArray *marray = [NSMutableArray array];
    if (array) {
        [marray addObjectsFromArray:array];
        if ([marray containsObject:obj]) {
            [marray removeObject:obj];
        }
    }
    if (marray.count) {
        [defaults setValue:marray forKey:key];
    }else{
        [defaults removeObjectForKey:key];
    }
    [defaults synchronize];
    return marray.count;
}
/**
 *	保存obj到本地
 *
 *	@param	obj	数据
 *	@param	key	键
 */
+ (void)saveToDefaults:(id)obj forKey:(NSString*)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:obj forKey:key];
    [defaults synchronize];
}

+ (id)defaultsForKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}
+ (void)removeForKey:(NSString*)key
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

+(NSData *)toPostData:(NSDictionary *)params
{
    NSString *postString=@"";
    for(NSString *key in [params allKeys])
    {
        NSString *value=[params objectForKey:key];
        postString=[postString stringByAppendingFormat:@"%@=%@&",key,value];
    }
    if([postString length]>1)
    {
        postString=[postString substringToIndex:[postString length]-1];
    }
    return [postString dataUsingEncoding:NSUTF8StringEncoding];
}
+(id)PostData:(NSDictionary*)dict forUrl:(NSString*)urlString
{
    if((!dict)||dict.allKeys.count==0)
    {
        return nil;
    }
    NSData* postData =[self toPostData:dict];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    
    NSURL *baseUrl = [NSURL URLWithString: urlString];
    
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:baseUrl
                                                                   cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                               timeoutInterval:8.0f];
    
    
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setURL:baseUrl];
    [urlRequest setValue: postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody: postData];
    
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection
                       sendSynchronousRequest:urlRequest
                       returningResponse: &response
                       error: &error];
    
    if (urlData) {
        NSDictionary *rlt = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingAllowFragments error:NULL];
        return rlt;
    }
    return nil;
}
+(id)PostImageData:(NSDictionary*)params forUrl:(NSString*)url{
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    UIImage *image=[params objectForKey:@"image"];
    //得到图片的data
    NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"image"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        }
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"logo\"; filename=\"logo.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%ld", (long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    /*建立连接，设置代理
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //设置接受response的data
    if (conn) {
        mResponseData = [[NSMutableData data] retain];
    }*/
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection
                       sendSynchronousRequest:request
                       returningResponse: &response
                       error: &error];
    
    if (urlData) {
        NSDictionary *rlt = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingAllowFragments error:NULL];
        NSLog(@"err:%@",rlt);
        return rlt;
    }
    return nil;
}


- (void)printViewHierarchy:(UIView *)superView
{
    static uint level = 0;
    for(uint i = 0; i < level; i++){
        printf("\t");
    }
    
    const char *className = NSStringFromClass([superView class]).UTF8String;
    const char *frame = NSStringFromCGRect(superView.frame).UTF8String;
    printf("%s:%s\n", className, frame);
    
    ++level;
    for(UIView *view in superView.subviews){
        [self printViewHierarchy:view];
    }
    --level;
}

@end
